//
//  TBHomeViewController.swift
//  新浪微博
//
//  Created by bin on 15/12/1.
//  Copyright © 2015年 XMG. All rights reserved.
//

import UIKit


enum TableViewCellIdentifier: String{
    case NormalCellIdentifier = "myCell"
    case ForwardCellIdentifier = "forwardCell"
    
    /// 根据模型获取cell的重用标识
    static func identifierWithViewModel(status: TBStatusViewModel) -> String
    {
        // rawValue 代表获取枚举的原始值
        return (status.status.retweeted_status != nil) ? ForwardCellIdentifier.rawValue : NormalCellIdentifier.rawValue
    }
}

class TBHomeViewController: TBBaseTableViewController {

    
    var viewModle  = TBHomeVCViewModel()
    var status: [TBStatusViewModel] {
        
        return viewModle.status
    }
    lazy var popTools: TBPopDelegteTool = {
        let tool = TBPopDelegteTool()
        return tool
    }()
    lazy var tipLabel:UILabel = {
        let label = UILabel()
        label.textAlignment = NSTextAlignment.Center
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

//        tableView.rowHeight = UITableViewAutomaticDimension
//        tableView.estimatedRowHeight = 300
        //1.如果未登录，设置访客界面
        if !isLogin{
            vistorView.setupContent(nil, title: nil)
            return
        }
        refreshControl = TBRefreshControl()
        refreshControl?.addTarget(viewModle, action: Selector("loadData"), forControlEvents: UIControlEvents.ValueChanged)

        setupNav()
        ///since_id	false	int64	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
        //max_id	false	int64
   
        viewModle.block = {
            (count) in ()
            self.tableView.reloadData()
            // 2.关闭刷新控件
            self.refreshControl?.endRefreshing()
            self.tipLabelAni(count)
        }
        viewModle.loadData()
        
        
        //2.注册监听
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("meBtnSelected"), name: "PopoverViewControllerShowNotification", object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("meBtnSelected"), name: "PopoverViewControllerDismissClickNotification", object: nil)
        
        tipLabel.backgroundColor = UIColor.orangeColor()
    navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - 内部控制方法
    
    private func tipLabelAni(text: String){
        tipLabel.text = text
        tipLabel.frame = CGRectMake(0, -64, ScreenW, 44)
        UIView.animateWithDuration(1, animations: { () -> Void in
            UIView.setAnimationRepeatAutoreverses(true)
            self.tipLabel.frame = CGRectMake(0, 44, ScreenW, 44)
            }) { (_) -> Void in
                self.tipLabel.frame = CGRectMake(0, -64, ScreenW, 44)
        }
    
    }
    
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: "navigationbar_friendattention", target: self, action: Selector("leftBarButtonItemClicked"))
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: "navigationbar_pop", target: self, action: Selector("rightBarButtonItemClicked"))
        
        let titleBtn = TBTitltButton()
        titleBtn.setTitle(TBUserAccount.userAccount?.screen_name, forState: .Normal)
        titleBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
        titleBtn.setImage(UIImage(named: "navigationbar_arrow_down"), forState: .Normal)
        titleBtn.setImage(UIImage(named: "navigationbar_arrow_up"), forState: .Selected)
        titleBtn.addTarget(self, action: Selector("meBtnClicked:"), forControlEvents: .TouchUpInside)
        titleBtn.sizeToFit()
        titleBtn.adjustsImageWhenHighlighted = false
        navigationItem.titleView = titleBtn
    }

    @objc private func meBtnClicked(btn: UIButton){
    
        let popoverVC = UIStoryboard(name: "TBPopoverViewController", bundle: nil).instantiateInitialViewController()!
        popoverVC.transitioningDelegate = popTools
        popoverVC.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(popoverVC, animated: true, completion: nil)
    }
    
    @objc private func meBtnSelected(){
        let btn = navigationItem.titleView as! UIButton
        btn.selected = !btn.selected
    }
    
    @objc private func leftBarButtonItemClicked(){
        print("left")
    }
    
    @objc private func rightBarButtonItemClicked(){
        let nav = UIStoryboard(name: "TBQRCodeViewController", bundle: nil).instantiateInitialViewController()!
        presentViewController(nav, animated: true, completion: nil)
    }

}

extension TBHomeViewController{
    // MARK: - Table view data source
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let aStatus = status[indexPath.row] as TBStatusViewModel
        var identi: String = ""
        if aStatus.status.retweeted_status != nil {
            identi = "forwardCell"
        }else{
            identi = "myCell"
        }
        
        let cell = tableView.dequeueReusableCellWithIdentifier(identi) as! TBStatusCell
        cell.status = aStatus
        return cell.heightForCell()
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return status.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let aStatus = status[indexPath.row] as TBStatusViewModel
        let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifier.identifierWithViewModel(aStatus)) as! TBStatusCell
        cell.status = aStatus
        if indexPath.row == status.count - 1{
            viewModle.isLoadMore = true
            viewModle.loadData()
        }
        return cell
        
    }
    
    
}



